import HomeHead from "@/components/HomeHead.jsx";
import { Divider, DotLoading, Image, SafeArea, Swiper } from "antd-mobile";
import React, { useEffect, useRef, useState } from "react";
import { Link } from "react-router-dom";
import _ from "../assets/utils";
import NewsItem from "../components/NewsItem";
import SkeletonAgain from "../components/SkeletonAgain";
import api from "../store/api";
import { useGetNewsLatestQuery } from "../store/api/Api";
import "./Home.less";

export default function Home() {
  // 日期数据
  let today = _.formatTime(null, "{0}{1}{2}");
  // 更多数据列表
  const [moreList, setmoreList] = useState([]);
  // "加载更多"的DOM
  const loadMore = useRef();
  // 加载数据
  const { data, isSuccess, isFetching, isError } = useGetNewsLatestQuery();

  // 第一次渲染完毕：设置监听器，实现触底加载
  useEffect(() => {
    let ob = new IntersectionObserver(async (changes) => {
      let { isIntersecting } = changes[0];
      if (isIntersecting) {
        try {
          let time = data.date;
          if (moreList.length > 0) {
            time = moreList[moreList.length - 1].date;
          }
          let res = await api.queryNewsBefore(time);
          moreList.push(res);
          setmoreList([...moreList]);
        } catch (_) {}
      }
    });
    let loadMoreBox = loadMore.current;
    ob.observe(loadMore.current);
    // 在组件释放的时候，手动销毁监听器
    return () => {
      ob.unobserve(loadMoreBox);
      ob = null;
    };
  }, [isSuccess]);

  return (
    <div className='home-box'>
      <HomeHead today={today || data.date} />
      {/* 轮播图 */}
      {isSuccess ? (
        <div className='swiper-box'>
          <Swiper autoplay>
            {data.top_stories.map((item) => {
              let { id, image, hint, title } = item;
              return (
                <Swiper.Item key={id}>
                  <Link to={{ pathname: `/detail/${id}` }}>
                    <Image src={image} lazy />
                    <div className='desc'>
                      <h3 className='title'>{title}</h3>
                      <p className='author'>{hint}</p>
                    </div>
                  </Link>
                </Swiper.Item>
              );
            })}
          </Swiper>
        </div>
      ) : null}
      {/* 骨架条 */}
      {isFetching && <SkeletonAgain />}
      {/* 刚开始的新闻列表 */}
      {isSuccess
        ? data.stories.map((item, index) => {
            return (
              <div className='news-box' key={index}>
                <div className='list'>
                  <NewsItem key={item.id} info={item} />
                </div>
              </div>
            );
          })
        : null}
      {/* 更多的新闻列表 */}
      {moreList.length > 0 &&
        moreList.map((item, index) => {
          let { date, stories } = item;
          return (
            <div className='news-box' key={index}>
              <Divider contentPosition='left'>
                {_.formatTime(date, "{1}月{2}日")}
              </Divider>
              <div className='list'>
                {stories.map((item) => {
                  return <NewsItem key={item.id} info={item} />;
                })}
              </div>
            </div>
          );
        })}
      {/* 加载更多,应该是利用了懒加载的模式，下拉刷新，上来加载 */}
      <div
        className='lodemore-box'
        ref={loadMore}
        // style={{ display: newsList.length === 0 ? "none" : "block" }}
      >
        <DotLoading color='white'></DotLoading>加载中
      </div>
      {/* 手机的底部安全区 */}
      <SafeArea position='bottom' />
    </div>
  );
}
